package com.jumi.microservice.wdt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.dto.wdt.WdtLogisticsRequest;
import com.jumi.microservice.dto.wdt.WdtLogisticsResponse;
import com.jumi.microservice.dto.wdt.WdtOrderRequest;
import com.jumi.microservice.entity.AfterSealOrder;
import com.jumi.microservice.service.admin.AdminSendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dirk
 * @Date 2020-08-20 14:50
 */
@Component
@RefreshScope
public class WdtOrderClient {

    private static final Logger log = LoggerFactory.getLogger(WdtOrderClient.class);

    @Resource
    private WdtClient wdtClient;

    @Value("${wdt.tradePush:/trade_push.php}")
    private String pushOrderUrl;

    @Value("${wdt.tradePush:/logistics_sync_query.php}")
    private String logisticsSyncQueryUrl;

    @Value("${wdt.tradePush:/logistics_sync_ack.php}")
    private String logisticsSyncAckUrl;

    @Value("${wdt.shopNo}")
    private String shopNo;

    @Resource
    private WdtRequestConvert wdtRequestConvert;

    @Resource
    private AdminSendService adminSendService;

    public void pushOrder(List<WdtOrderRequest> wdtOrderRequestList) {
        List<Map<String, Object>> tradeList = wdtRequestConvert.orderListConvert(wdtOrderRequestList);
        Map<String, Object> params = new HashMap<>();
        params.put("shop_no", shopNo);
        params.put("trade_list", JSON.toJSONString(tradeList, SerializerFeature.WriteDateUseDateFormat));
        String response = null;
        try {
            log.info("wdt push order : params => [{}]", JSON.toJSONString(params));
            response = wdtClient.execute(pushOrderUrl, params);
            log.info("wdt push order : response => [{}]", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getInteger("code") != 0) {
            throw new BaseException(jsonObject.getInteger("code"), jsonObject.getString("message"));
        }
    }

    public void logisticsSync() {
        Map<String, Object> params = new HashMap<>();
        params.put("limit", 100);
        String response = null;
        try {
            log.info("wdt logistics sync query : params => [{}]", JSON.toJSONString(params));
            response = wdtClient.execute(logisticsSyncQueryUrl, params);
            log.info("wdt logistics sync query : response => [{}]", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getInteger("code") != 0) {
            throw new BaseException(jsonObject.getInteger("code"), jsonObject.getString("message"));
        }
        JSONArray jsonArray = jsonObject.getJSONArray("trades");
        List<WdtLogisticsResponse> logisticsResponseList = jsonArray.toJavaList(WdtLogisticsResponse.class);
        if (logisticsResponseList.isEmpty()) {
            return;
        }

        List<AfterSealOrder> afterSealOrderList = new ArrayList<>();
        List<WdtLogisticsRequest> wdtLogisticsRequestList = new ArrayList<>();
        logisticsResponseList.forEach(wdtLogisticsResponse -> {
            if (!wdtLogisticsResponse.getTid().startsWith("JM")) {
                // 包裹发货
                AfterSealOrder afterSealOrder = new AfterSealOrder();
                afterSealOrder.setOrderNo(wdtLogisticsResponse.getTid());
//                afterSealOrder.setExpressCompany(wdtLogisticsResponse.getLogistics_type())
//                afterSealOrder.setRemark(wdtLogisticsResponse.getLogistics_name())
                // 借用remark字段传递快递公司名称
                afterSealOrder.setRemark(wdtLogisticsResponse.getLogistics_name_erp());
                afterSealOrder.setRealLogisticsNo(wdtLogisticsResponse.getLogistics_no());
                afterSealOrderList.add(afterSealOrder);
                // 物流同步回写
                WdtLogisticsRequest wdtLogisticsRequest = new WdtLogisticsRequest();
                wdtLogisticsRequest.setRecId(wdtLogisticsResponse.getRec_id());
                wdtLogisticsRequest.setStatus(new Byte("1"));
                wdtLogisticsRequestList.add(wdtLogisticsRequest);
            }
        });
        adminSendService.updateAfterOrderStatus(afterSealOrderList);
        adminSendService.updateAfterOrderGoodsStatusByOrderNo(afterSealOrderList);
//        adminSendService.batchNoticeMaterial(afterSealOrderList);

        Map<String, Object> ackParams = new HashMap<>();
        ackParams.put("logistics_list", JSON.toJSONString(wdtRequestConvert.logisticsListConvert(wdtLogisticsRequestList)));
        String ackResponse = null;
        try {
            log.info("wdt logistics sync ack : params => [{}]", JSON.toJSONString(ackParams));
            ackResponse = wdtClient.execute(logisticsSyncAckUrl, ackParams);
            log.info("wdt logistics sync ack : response => [{}]", ackResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject ackJsonObject = JSONObject.parseObject(ackResponse);
        if (ackJsonObject.getInteger("code") != 0) {
            throw new BaseException(ackJsonObject.getInteger("code"), ackJsonObject.getString("message"));
        }
    }
}
